<template>
  <view class="shop-detail">
    <!-- 店铺基本信息 -->
    <view class="shop-info">
      <image class="shop-logo" :src="shopInfo.shopLogo" mode="aspectFill"></image>
      <view class="info-content">
        <text class="shop-name">{{ shopInfo.shopName }}</text>
        <text class="shop-desc">{{ shopInfo.shopDescription }}</text>
        <view class="shop-stats">
          <text>商品数: {{ shopInfo.productCount }}</text>
          <text class="divider">|</text>
          <text>月销量: {{ shopInfo.monthlySales }}</text>
          <text class="divider">|</text>
          <text>总销量: {{ shopInfo.totalSales }}</text>
        </view>
      </view>
    </view>

    <!-- 店铺公告 -->
    <view class="shop-notice" v-if="shopInfo.notice">
      <text class="notice-title">店铺公告</text>
      <text class="notice-content">{{ shopInfo.notice }}</text>
    </view>

    <!-- 商家信息 -->
    <view class="business-info">
      <view class="info-item">
        <text class="label">营业时间</text>
        <text class="value">{{ shopInfo.businessHours || '暂无' }}</text>
      </view>
      <view class="info-item">
        <text class="label">联系电话</text>
        <text class="value">{{ shopInfo.contactPhone || '暂无' }}</text>
      </view>
      <view class="info-item">
        <text class="label">联系邮箱</text>
        <text class="value">{{ shopInfo.contactEmail || '暂无' }}</text>
      </view>
      <view class="info-item">
        <text class="label">店铺地址</text>
        <text class="value">{{ shopInfo.address || '暂无' }}</text>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="products-section">
      <view class="section-header">
        <text class="title">店铺商品</text>
        <view class="filter-tabs">
          <text 
            v-for="tab in filterTabs" 
            :key="tab.value"
            :class="['tab-item', { active: currentSort === tab.value }]"
            @click="handleSortChange(tab.value)"
          >{{ tab.label }}</text>
        </view>
      </view>
      
      <!-- 商品瀑布流 -->
      <waterfall-flow 
        v-if="products.list.length > 0"
        :products="products.list"
        @item-click="toProductDetail"
        @all-images-loaded="onImagesLoaded"
      ></waterfall-flow>

      <!-- 空状态 -->
      <view v-else class="empty-state">
        <text>暂无商品</text>
      </view>

      <!-- 加载更多 -->
      <uni-load-more :status="loadMoreStatus"></uni-load-more>
    </view>
  </view>
</template>

<script>
import api from '@/config/api'
import WaterfallFlow from '@/components/common/WaterfallFlow.vue'

export default {
  components: {
    WaterfallFlow
  },
  data() {
    return {
      shopId: null,
      shopInfo: {
        id: null,
        shopName: '',
        shopLogo: '',
        shopDescription: '',
        notice: '',
        businessHours: '',
        score: 0,
        monthlySales: 0,
        totalSales: 0,
        productCount: 0,
        isRecommend: 0,
        address: '',
        contactPhone: '',
        contactEmail: '',
        level: 0,
        afterSalePolicy: '',
        createTime: null
      },
      products: {
        list: [],
        total: 0,
        current: 1,
        size: 10
      },
      currentSort: 'new',
      filterTabs: [
        { label: '新品', value: 'new' },
        { label: '销量', value: 'sales' },
        { label: '价格', value: 'price' }
      ],
      loadMoreStatus: 'more',
      isLoading: false
    }
  },
  onLoad(options) {
    if (!options.id) {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
    
    this.shopId = options.id
    this.loadShopDetail()
    this.loadProducts(true)
  },
  onPullDownRefresh() {
    this.refresh()
  },
  onReachBottom() {
    if (this.loadMoreStatus === 'more') {
      this.loadProducts()
    }
  },
  methods: {
    // 加载店铺详情
    async loadShopDetail() {
      try {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        
        const res = await api.shop.detail(this.shopId)
        
        if (res.code === 200 && res.data) {
          this.shopInfo = {
            ...this.shopInfo,
            ...res.data
          }
        } else {
          throw new Error(res.message || '加载失败')
        }
      } catch (error) {
        console.error('加载店铺详情失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 加载商品列表
    async loadProducts(refresh = false) {
      if (this.isLoading) return
      
      try {
        this.isLoading = true
        this.loadMoreStatus = 'loading'
        
        if (refresh) {
          this.products.current = 1
        }
        
        const params = {
          pageNum: this.products.current,
          pageSize: this.products.size,
          sortBy: this.currentSort
        }
        
        const res = await api.shop.getProducts(this.shopId, params)
        
        if (res.code === 200 && res.data) {
          const { records, total } = res.data
          
          // 处理商品数据，对齐数据结构
          const processedProducts = records.map(item => ({
            id: item.id,
            name: item.name,
            description: item.description,
            price: item.price,
            mainImage: item.mainImage,
            status: item.status,
            favorite: item.favorite,
            favoriteTime: item.favoriteTime,
            sales: item.sales || 0
          }))
          
          if (refresh) {
            this.products.list = processedProducts
          } else {
            this.products.list = [...this.products.list, ...processedProducts]
          }
          
          this.products.total = total
          this.loadMoreStatus = records.length < this.products.size ? 'noMore' : 'more'
          
          if (!refresh) {
            this.products.current++
          }
        } else {
          throw new Error(res.message || '加载失败')
        }
      } catch (error) {
        console.error('加载商品列表失败:', error)
        this.loadMoreStatus = 'more'
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
        if (uni.stopPullDownRefresh) {
          uni.stopPullDownRefresh()
        }
      }
    },
    
    // 刷新数据
    refresh() {
      this.loadShopDetail()
      this.loadProducts(true)
    },
    
    // 切换排序方式
    handleSortChange(sort) {
      if (this.currentSort === sort) return
      this.currentSort = sort
      this.loadProducts(true)
    },
    
    // 跳转到商品详情
    toProductDetail(product) {
      uni.navigateTo({
        url: `/pages/product/detail/index?id=${product.id}`
      })
    },
    
    // 图片加载完成
    onImagesLoaded() {
      // 可以在这里处理图片加载完成后的逻辑
    }
  }
}
</script>

<style lang="scss" scoped>
.shop-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20rpx;
}

.shop-info {
  background-color: #fff;
  padding: 30rpx;
  display: flex;
  margin-bottom: 20rpx;

  .shop-logo {
    width: 120rpx;
    height: 120rpx;
    border-radius: 12rpx;
    margin-right: 20rpx;
  }

  .info-content {
    flex: 1;

    .shop-name {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 10rpx;
    }

    .shop-desc {
      font-size: 26rpx;
      color: #666;
      margin-bottom: 16rpx;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .shop-stats {
      font-size: 24rpx;
      color: #999;

      .divider {
        margin: 0 16rpx;
        color: #eee;
      }
    }
  }
}

.shop-notice {
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;

  .notice-title {
    font-size: 28rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 12rpx;
  }

  .notice-content {
    font-size: 26rpx;
    color: #666;
    line-height: 1.5;
  }
}

.business-info {
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;

  .info-item {
    display: flex;
    align-items: center;
    padding: 12rpx 0;

    .label {
      font-size: 26rpx;
      color: #333;
      width: 140rpx;
    }

    .value {
      flex: 1;
      font-size: 26rpx;
      color: #666;
    }
  }
}

.products-section {
  background-color: #fff;
  padding: 20rpx 0;

  .section-header {
    padding: 0 30rpx 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid #f5f5f5;

    .title {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }

    .filter-tabs {
      display: flex;
      gap: 30rpx;

      .tab-item {
        font-size: 26rpx;
        color: #666;
        position: relative;

        &.active {
          color: #ff5500;
          font-weight: 500;

          &::after {
            content: '';
            position: absolute;
            left: 50%;
            bottom: -6rpx;
            transform: translateX(-50%);
            width: 30rpx;
            height: 4rpx;
            background-color: #ff5500;
            border-radius: 2rpx;
          }
        }
      }
    }
  }
}

.empty-state {
  padding: 60rpx 0;
  text-align: center;

  text {
    font-size: 28rpx;
    color: #999;
  }
}
</style> 